<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="fr">
        <el-button
          v-if="!matchScope.pullData"
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          @click="addMatchSchedule(matchScope.id, matchScope.multiType)"
          >添加场次</el-button
        >
        <el-upload
          v-if="matchScope.pullData"
          class="filter-item"
          action="#"
          @click.native="setMatchId(matchScope.id)"
          :before-upload="beforeUpload"
          :show-file-list="false"
          :file-list="fileList"
        >
          <el-button style="margin-left: 10px" type="primary"
            >导入场次</el-button
          >
        </el-upload>
        <el-button
          v-if="matchScope.pullData"
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          >下载模板</el-button
        >
        <el-button
          class="filter-item"
          style="margin-left: 10px"
          @click="handleCreate"
          type="primary"
          icon="el-icon-edit"
          >添加</el-button
        >
      </div>
    </div>
    <el-table
      class="tqd_table"
      :key="tableKey"
      :data="list"
      v-loading="listLoading"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <!-- <el-table-column
      align="center"
      type="selection"
      width="55">
    	</el-table-column> -->
      <el-table-column width="60" prop="id" label="序号" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="名称" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.placeName }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <router-link
            :to="
              '/sys/match/schedule/list?matchId=' +
              scope.row.matchId +
              '&matchPlaceId=' +
              scope.row.id
            "
          >
            <el-button type="primary" size="mini">场次管理</el-button>
          </router-link>
          <!-- <el-button size="mini" type="success" @click="handleModifyStatus(scope.row,'draft')">修改</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[15,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div> -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="550px"
      :close-on-click-modal="false"
    >
      <el-form
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 100%"
      >
        <el-form-item label="场地名称" prop="placeName">
          <el-input v-model="temp.placeName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="记录台数理" prop="name">
          <el-input v-model.Number="temp.name" type="number"></el-input>
        </el-form-item> -->
        <!-- <el-form-item prop="refereeMode" label="裁判制式">
					<el-select class="filter-item" v-model="temp.refereeMode" placeholder="请选择">
            <el-option value="3" label='三裁'>三裁</el-option>
            <el-option value="5" label='五裁'>五裁</el-option>
            <el-option value="7" label='七裁'>七裁</el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("table.cancel")
        }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
          >{{ $t("table.confirm") }}</el-button
        >
        <el-button v-else type="primary" @click="updateData">{{
          $t("table.confirm")
        }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加 -->
    <el-dialog
      title="添加场次"
      :visible.sync="addMatchScheduleDialog"
      width="950px"
      @open="getMatchScoreRuleList"
      :close-on-click-modal="false"
    >
      <el-table
        class="tqd_table"
        :key="tableKey"
        :data="addSesionList"
        v-loading="listLoading"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          align="center"
          label="比赛场地"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <!-- <el-input class="article-textarea"  style="width:110px;"  v-model="scope.row.matchPlaceId"></el-input>	 -->
            <el-select
              v-model="scope.row.matchPlaceId"
              placeholder="请选择"
              style="width: 100px"
            >
              <el-option
                v-for="item in matchPlaceList"
                :key="item.id"
                :value="item.id"
                :label="item.placeName"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="比赛类型代码"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-input
              class="article-textarea"
              style="width: 110px"
              v-model="scope.row.typeCode"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="拉取开始位置"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-input
              class="article-textarea"
              style="width: 110px"
              v-model="scope.row.rangeStart"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="拉取结束位置"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-input
              class="article-textarea"
              style="width: 110px"
              v-model="scope.row.rangeEnd"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="比赛类型"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.matchType"
              placeholder="请选择"
              style="width: 100px"
            >
              <el-option value="2" label="对阵"></el-option>
              <el-option value="1" label="表演"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="是否双品势"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isTwo"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
            <el-button type="text" @click="scope.row.isTwo = !scope.row.isTwo">
              <span v-if="scope.row.isTwo">是</span>
              <span v-else>不是</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="裁判规则">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.refereeType"
              placeholder="请选择"
              style="width: 100px"
            >
              <el-option
                v-for="item in matchScoreRuleList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addMatchScheduleDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="createScheduleByOnline"
          :loading="createScheduleByOnlineLoading"
          >确定</el-button
        >
        <!-- <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button> -->
      </div>
    </el-dialog>
    <el-dialog
      title="删除"
      :visible.sync="deleteMatchScheduleDialog"
      width="350px"
      :close-on-click-modal="false"
    >
      <el-form label-position="left" label-width="100px" style="width: 100%">
        <el-form-item label="密码">
          <el-input v-model="currentPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteMatchScheduleDialog = false">取消</el-button>
        <!-- <el-button type="primary" @click="confirmPasswordBtn">确定</el-button> -->
        <el-button type="primary" >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getMatchPlaceList, saveMatchPlace } from '@/api/matchPlace'
import { getMatchInfo } from '@/api/match'
import { getMatchScoreRuleList } from '@/api/matchScoreRule'
import { createScheduleByOnline, importSchedule } from '@/api/matchSchedule'
import waves from '@/directive/waves' // 水波纹指令
import { showMsg } from '@/utils'
export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      uploadMatchId: null,
      listLoading: true,
      addMatchScheduleDialog: false,
      matchScoreRuleList: null,
      listQuery: {
        matchId: null
      },
      temp: {
        matchId: null,
        placeName: null,
        matchName: null, // 比赛名称
        matchTime: null, // 比赛时间
        pullDataUrl: null, // 数据地址
        placeCount: 1, // 场地数量
        matchCode: null, // 赛事代码
        refereeType: null, // 裁判人数
        multiType: false, // 是否多锁
        pullData: false, // 是否联网
        id: undefined
      },
      dialogFormVisible: false,
      dialogPvVisible: false,
      downloadLoading: false,
      matchScope: null,
      editMatch: {
        matchId: null,
        matchName: null, // 比赛名称
        matchTime: null, // 比赛时间
        pullDataUrl: null, // 数据地址
        matchProject: [] // 比赛项目
      },
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      pvData: [],
      rules: {
        matchName: [{ required: true, message: '必填', trigger: 'blur' }],
        matchTime: [{ required: true, message: '必选', trigger: 'blur' }],
        matchCode: [{ required: true, message: '必填', trigger: 'blur' }],
        pullDataUrl: [{ required: true, message: '必填', trigger: 'blur' }],
        placeCount: [{ required: true, message: '必填', trigger: 'blur' }],
        refereeType: [{ required: true, message: '必选', trigger: 'change' }]
      },
      loadSign: true,
      page: 1,
      createScheduleByOnlineLoading: false,
      matchPlaceList: [],
      deleteMatchScheduleDialog: false,
      currentPassword: ''
    }
  },
  created() {
    this.listQuery.matchId = this.$route.query.id
    this.getList()
    this.getData()
  },
  methods: {
    getList() {
      this.listLoading = true
      getMatchPlaceList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getData() {
      getMatchInfo({ matchId: this.listQuery.matchId }).then((res) => {
        this.matchScope = res.data.data
      })
    },
    createScheduleByOnline() {
      if (this.createScheduleByOnlineLoading) {
        return
      }
      var obj = []
      for (var i in this.addSesionList) {
        if (this.addSesionList[i].matchPlaceId != null) {
          if (
            this.addSesionList[i].typeCode === null ||
            this.addSesionList[i].rangeStart === null ||
            this.addSesionList[i].rangeEnd === null ||
            this.addSesionList[i].matchType === null ||
            this.addSesionList[i].refereeType === null
          ) {
            showMsg('提交的数据不完整', 2)
            return false
          }

          obj.push(Object.assign({}, this.addSesionList[i]))
        }
      }
      if (obj.length === 0) {
        showMsg('提交的数据不完整', 2)
        return
      }
      this.createScheduleByOnlineLoading = true
      createScheduleByOnline(obj).then((res) => {
        this.createScheduleByOnlineLoading = false
        if (res.data.code === 0) {
          this.dialogFormVisible = false
          showMsg(res.data.message, 1)
        } else {
          showMsg(res.data.message, 2)
        }
      })
    },
    addSesionListItem(id, multiType) {
      this.addSesionList.push({
        matchId: id,
        typeCode: null,
        matchPlaceId: null,
        rangeStart: null,
        rangeEnd: null,
        matchType: null,
        multiType: multiType,
        refereeType: null,
        // pullData: null,
        isTwo: null
      })
    },
    addMatchSchedule(id, multiType) {
      getMatchPlaceList({ matchId: id }).then((response) => {
        this.matchPlaceList = response.data.data
      })
      this.addSesionList = []
      for (var i = 0; i < 10; i++) {
        this.addSesionListItem(id, multiType)
      }
      this.addMatchScheduleDialog = true
    },
    setMatchId(id) {
      this.uploadMatchId = id
    },
    getMatchScoreRuleList() {
      getMatchScoreRuleList().then((response) => {
        this.matchScoreRuleList = response.data.data
      })
    },
    beforeUpload: function(file) {
      console.log(file)
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$message.error()
        showMsg('上传文件只能是 xls或xlsx 格式!', 2)
        return false
      }

      var fd = new window.FormData()
      fd.append('matchId', this.uploadMatchId)
      fd.append('file', file)
      importSchedule(fd).then((res) => {
        if (res.data.code === 0) {
          this.dialogFormVisible = false
          showMsg(res.data.message, 1)
        } else {
          showMsg(res.data.message, 2)
        }
      })
      return false // 返回false不会自动上传
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        matchId: null,
        placeName: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.matchId = Number(this.$route.query.id)
          saveMatchPlace(this.temp).then((res) => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
            } else {
              showMsg(res.data.message, 2)
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
        }
      })
    },
    handleDelete(row) {
      this.$prompt('请输入密码', '确认删除？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$message({
            type: 'success',
            message: '你的密码是: ' + value
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    }
  }
}
</script>
